package com.njpi.stu.attendance.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.google.gson.Gson;
import com.njpi.stu.attendance.entity.Password;
import com.njpi.stu.attendance.entity.User;
import com.njpi.stu.attendance.service.IUserService;
import com.njpi.stu.utils.SendSms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;

/**
 * <p>
 * 人员表 前端控制器
 * </p>
 *
 * @author pxl
 * @since 2019-11-06
 */
@Controller
@RequestMapping("user")
public class UserController {


    /**
     * 修改用户个人信息
     * @param user
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/info",method = RequestMethod.PUT)
    public String changeInfo(@RequestBody User user,HttpSession session){
        String userNum=user.getUserNum();
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("user_num",userNum);
        User user1 = userService.getOne(queryWrapper);
        if(user1!=null){
            user.setUserId(user1.getUserId());
            user.setUserNum(userNum);
            boolean b = userService.updateById(user);
            User user2 = userService.getById(user1.getUserId());
            session.setAttribute("user",user2);
        }
        return "修改成功";
    }


    /**
     * 跳转用户个人信息页
     * @param model
     * @return
     */
    @RequestMapping(value = "/info",method = RequestMethod.GET)
    public String skipInfoPage(Model model){
        model.addAttribute("title","个人信息");
        return "info";
    }


    /**
     * 校验并修改密码
     * @param userNum
     * @param oldPwd
     * @param newPwd
     * @return
     */
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @ResponseBody
    @RequestMapping(value = "/password/{userNum}",method = RequestMethod.PUT)
    public String changePassword(@PathVariable("userNum") String userNum, @RequestBody Password password){
        //根据学号查询密码
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("user_num",userNum);
        User user = userService.getOne(queryWrapper);
        boolean matches = bCryptPasswordEncoder.matches(password.getOldPwd(),user.getPassword());
        if(matches){
           user.setPassword(bCryptPasswordEncoder.encode(password.getNewPwd()));
           userService.updateById(user);
            return "passwordSuccess";
        }else {
            return "passwordError";
        }
    }

    /**
     * 跳转修改密码页面
     * @param model
     * @return
     */
    @RequestMapping(value = "/password")
    public String skipPasswordPage(Model model){
        model.addAttribute("title","修改密码");
        return "password";
    }


    /**
     * 跳转注册页
     * @return
     */
    @RequestMapping(value = "/register",method = RequestMethod.GET)
    public String skipRegister(){
        return "register";
    }


    @Autowired
    private IUserService userService;


    /**
     * 用户注册
     * @param user
     * @param httpSession
     * @param verCode
     * @return
     */
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public String register(User user,HttpSession httpSession,String verCode){
        user.setType(1);
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        //填写时间
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());

        //保存注册信息，为开启短信验证
        boolean b = userService.save(user);
        //验证码判断，默认不开启此功能，若配置文件已经修改则可删除注解
        /*String randomCode = (String) httpSession.getAttribute("code");
        if(randomCode!=null && !randomCode.equals("")){
            if(randomCode.equals(verCode)){
                userService.save(user);
            }
        }*/
        return "redirect:/login";
    }


    /**
     *查询用户是否存在
     * @param userNum
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/register/{userNum}",method = RequestMethod.GET)
    public String selectOne(@PathVariable("userNum") String userNum){
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("user_num",userNum);
        User one = userService.getOne(queryWrapper);
        if(one!=null){
            return "该用户以存在";
        }
        return null;
    }



    @Autowired
    private SendSms sendSms;

    /**
     * 发送手机短信
     * 默认不开启此功能，若配置文件已经修改则可删除注解
     * @param phoneNu
     * @param session
     * @return
     */
   /* @ResponseBody
    @RequestMapping(value = "/sendSms/{phoneNu}",method = RequestMethod.GET)
    public String sendSms(@PathVariable("phoneNu") String phoneNu, HttpSession session){

        session.removeAttribute("code");
        //发送短信
        int code= (int) Math.ceil(Math.random()*10000);
        System.out.println(code);
        session.setAttribute("code",String.valueOf(code));
        //设置有效时间5分钟
        session.setMaxInactiveInterval(60*5);
        HashMap templateParamHash=new HashMap();
        templateParamHash.put("code",String.valueOf(code));
        Gson gson=new Gson();
        String  templateParam = gson.toJson(templateParamHash);
        HashMap<String,String> param=new HashMap<>();
        param.put("TemplateParam",templateParam);
        param.put("PhoneNumbers",phoneNu);
        try {
            sendSms.sendMsm(param);
            return "发送成功";
        } catch (Exception e) {
            return "发送失败";
        }
    }*/




}
